const app = getApp();
const db = wx.cloud.database();
const _ = db.command;
Page({
    data: {
        productId: '',
        productName: '',
        productImage: '',
        releaseDate: '',
        releasePrice: 0,
        releaseCount: 0,
        posts: [],
        productInfo: {},
        postList: [],
        goodsList: [],
        priceTrend: [],
        isLoading: true,
        showTooltip: false,
        tooltipDate: "",
        tooltipPrice: "",
        tooltipLeft: "",
        tooltipTop: "",
        isWanted: false,
        userInfo:{}
    },
    onLoad(options) {
        const userInfo = wx.getStorageSync('userInfo');
        this.setData({
            userInfo
        });
        if (options.productId) {
            this.setData({
                productId: options.productId
            });
            this.loadProductDetail();
            this.loadRelatedPosts();
            this.loadGoodsList();
            this.loadPriceTrend();
            this.checkWantStatus();
        } else {
            wx.showToast({
                title: '参数错误',
                icon: 'none',
                success: () => {
                    setTimeout(() => {
                        wx.navigateBack();
                    }, 1500);
                }
            });
        }
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.loadGoodsList();
        this.loadPriceTrend();
    },
    // 检查想要状态
    checkWantStatus() {
        const {
            productId,
            userInfo
        } = this.data;
        if (!userInfo) return; // 未登录时不检查

        wx.cloud.callFunction({
            name: 'checkProductWantStatus',
            data: {
                productId: productId,
                userId: userInfo._id
            },
            success: res => {
                console.log(res);
                if (res.result && res.result.success) {
                    this.setData({
                        isWanted: res.result.isWanted
                    });
                }
            },
            fail: err => {
                console.error('查询想要状态失败', err);
            }
        });
    },

    // 处理想要按钮点击
    handleWant() {
        const {
            productId,
            productName,productImage,
            userInfo
        } = this.data;
        // 未登录处理
        if (!userInfo) {
            wx.showModal({
                title: '提示',
                content: '请先登录后再操作',
                showCancel: false,
                success: () => {
                    wx.navigateTo({
                        url: '/pages/login/index'
                    });
                }
            });
            return;
        }

        wx.showLoading({
            title: '处理中...'
        });

        wx.cloud.callFunction({
            name: 'toggleProductWant',
            data: {
                productId: productId,
                productName: productName,
                productImage: productImage,
                userId: userInfo._id
            },
            success: res => {
                wx.hideLoading();

                if (res.result && res.result.success) {
                    this.setData({
                        isWanted: res.result.isWanted
                    });

                    // 更新产品想要数
                    this.setData({
                        'productInfo.wantCount': res.result.isWanted ?
                            this.data.productInfo.wantCount + 1 :
                            this.data.productInfo.wantCount - 1
                    });

                    wx.showToast({
                        title: res.result.isWanted ? '已加入想要' : '已取消想要',
                        icon: 'none'
                    });
                } else {
                    wx.showToast({
                        title: res.result.message || '操作失败',
                        icon: 'none'
                    });
                }
            },
            fail: err => {
                wx.hideLoading();
                console.error('切换想要状态失败', err);
                wx.showToast({
                    title: '操作失败',
                    icon: 'none'
                });
            }
        });
    },
    // 加载产品详情
    loadProductDetail() {
        db.collection('blindbox_products')
            .where({
                productId: this.data.productId
            })
            .get()
            .then(res => {
                if (res.data.length > 0) {
                    const productInfo = res.data[0];
                    // 设置导航栏标题
                    wx.setNavigationBarTitle({
                        title: productInfo.productName
                    });
                    let time = productInfo.releaseDate
                    const date = new Date(time);
                    const formattedDate = date.toISOString().split('T');
                    if (formattedDate.length > 0) {
                        productInfo.time = formattedDate[0]
                    }
                    this.setData({
                        productInfo
                    });
                } else {
                    throw new Error('未找到该产品信息');
                }
            })
            .catch(err => {
                console.error('加载产品详情失败:', err);
                wx.showToast({
                    title: '加载失败',
                    icon: 'none'
                });
            });
    },

    // 加载相关帖子
    loadRelatedPosts() {
        wx.showLoading({
            title: '加载中...'
        });

        wx.cloud.callFunction({
            name: 'getHotPostsByProduct',
            data: {
                productId: this.data.productId
            },
            success: res => {
                wx.hideLoading();
                console.log(res);
                if (res.result && res.result.success) {
                    this.setData({
                        postList: res.result.data
                    });
                } else {
                    wx.showToast({
                        title: res.result.message || '获取热度帖子失败',
                        icon: 'none'
                    });
                }
            },
            fail: err => {
                wx.hideLoading();
                console.error('获取热度帖子失败', err);
                wx.showToast({
                    title: '获取热度帖子失败',
                    icon: 'none'
                });
            }
        });
    },

    // 加载商品列表
    loadGoodsList() {
        db.collection('blindbox_goods')
            .where({
                productId: this.data.productId,
                status: true
            })
            .orderBy('createTime', 'desc')
            .get()
            .then(res => {
                console.log(res);
                res.data.forEach(item => {
                    let arr = item.goodsImage.split(',')
                    if (arr.length) {
                        item.image = arr[0]
                    }
                })
                this.setData({
                    goodsList: res.data
                });
            })
            .catch(err => {
                console.error('加载商品列表失败:', err);
            });
    },

    // 加载价格趋势
    loadPriceTrend() {
        const productId = this.data.productId;
        if (!productId) return;

        wx.showLoading({
            title: '加载价格趋势...',
            mask: true
        });

        wx.cloud.callFunction({
            name: 'getPriceTrend',
            data: {
                productId
            }
        }).then(res => {
            console.log(res);
            wx.hideLoading();
            if (res.result && res.result.success) {
                this.setData({
                    priceTrend: res.result.data.details,
                    showPriceTrend: true
                });
                this.drawPriceTrend()
            } else {
                wx.showToast({
                    title: res.result.message || '获取价格趋势失败',
                    icon: 'none'
                });
            }
        }).catch(err => {
            wx.hideLoading();
            console.error('获取价格趋势失败', err);
            wx.showToast({
                title: '网络错误，请稍后再试',
                icon: 'none'
            });
        });
    },

    drawPriceTrend() {
        const {
            priceTrend
        } = this.data;
        console.log(priceTrend);
        if (!priceTrend || priceTrend.length === 0) {
            console.warn('没有价格趋势数据');
            return;
        }

        // 获取Canvas上下文
        const ctx = wx.createCanvasContext('priceTrend');

        // 获取Canvas尺寸
        const query = wx.createSelectorQuery();
        query.select('.trend-chart')
            .boundingClientRect(rect => {
                const width = rect.width;
                const height = rect.height;

                // 图表边距
                const margin = {
                    top: 20,
                    right: 30,
                    bottom: 40,
                    left: 40
                };
                const chartWidth = width - margin.left - margin.right;
                const chartHeight = height - margin.top - margin.bottom;

                // 计算数据范围
                const prices = priceTrend.map(item => item.avgPrice);
                const minPrice = Math.min(...prices);
                const maxPrice = Math.max(...prices);
                const priceRange = maxPrice - minPrice;

                // 确保Y轴有一定余量
                const padding = priceRange * 0.1 || 5;
                const adjustedMinPrice = Math.floor(minPrice - padding);
                const adjustedMaxPrice = Math.ceil(maxPrice + padding);

                // 格式化日期
                const dates = priceTrend.map(item => {
                    const date = new Date(item.date);
                    return `${date.getMonth() + 1}/${date.getDate()}`;
                });

                // 绘制背景
                ctx.setFillStyle('#f8f8f8');
                ctx.fillRect(0, 0, width, height);

                // 绘制坐标轴
                this.drawAxes(ctx, margin, width, height, dates, adjustedMinPrice, adjustedMaxPrice);

                // 绘制网格线
                this.drawGridLines(ctx, margin, chartWidth, chartHeight, dates.length, 5, adjustedMinPrice, adjustedMaxPrice);

                // 绘制折线和数据点
                this.drawLineAndPoints(ctx, margin, chartWidth, chartHeight, priceTrend, adjustedMinPrice, adjustedMaxPrice);

                // 绘制图例
                this.drawLegend(ctx, width, height);

                // 执行绘制
                ctx.draw();

                // 保存图表信息用于交互
                this.setData({
                    chartInfo: {
                        margin,
                        width,
                        height,
                        chartWidth,
                        chartHeight,
                        minPrice: adjustedMinPrice,
                        maxPrice: adjustedMaxPrice,
                        priceTrend
                    }
                });
            })
            .exec();
    },

    // 绘制坐标轴
    drawAxes(ctx, margin, width, height, dates, minPrice, maxPrice) {
        // X轴
        ctx.beginPath();
        ctx.setStrokeStyle('#e5e5e5');
        ctx.setLineWidth(1);
        ctx.moveTo(margin.left, height - margin.bottom);
        ctx.lineTo(width - margin.right, height - margin.bottom);
        ctx.stroke();

        // Y轴
        ctx.beginPath();
        ctx.moveTo(margin.left, margin.top);
        ctx.lineTo(margin.left, height - margin.bottom);
        ctx.stroke();

        // X轴刻度和标签
        const xStep = (width - margin.left - margin.right) / (dates.length - 1);
        dates.forEach((date, index) => {
            const x = margin.left + index * xStep;

            // 刻度线
            ctx.beginPath();
            ctx.moveTo(x, height - margin.bottom);
            ctx.lineTo(x, height - margin.bottom + 5);
            ctx.stroke();

            // 标签
            ctx.setFontSize(10);
            ctx.setTextAlign('center');
            ctx.setTextBaseline('top');
            ctx.setFillStyle('#666');
            ctx.fillText(date, x, height - margin.bottom + 10);
        });

        // Y轴刻度和标签
        const ySteps = 5;
        const yStep = (height - margin.top - margin.bottom) / ySteps;
        const priceStep = (maxPrice - minPrice) / ySteps;

        for (let i = 0; i <= ySteps; i++) {
            const y = height - margin.bottom - i * yStep;
            const price = minPrice + i * priceStep;

            // 刻度线
            ctx.beginPath();
            ctx.moveTo(margin.left, y);
            ctx.lineTo(margin.left - 5, y);
            ctx.stroke();

            // 标签
            ctx.setFontSize(10);
            ctx.setTextAlign('right');
            ctx.setTextBaseline('middle');
            ctx.setFillStyle('#666');
            ctx.fillText(price.toFixed(0), margin.left - 10, y);
        }
    },

    // 绘制网格线
    drawGridLines(ctx, margin, chartWidth, chartHeight, xCount, yCount, minPrice, maxPrice) {
        ctx.setStrokeStyle('#f0f0f0');
        ctx.setLineWidth(1);

        // 垂直网格线
        const xStep = chartWidth / (xCount - 1);
        for (let i = 0; i < xCount; i++) {
            const x = margin.left + i * xStep;
            ctx.beginPath();
            ctx.moveTo(x, margin.top);
            ctx.lineTo(x, margin.top + chartHeight);
            ctx.stroke();
        }

        // 水平网格线
        const yStep = chartHeight / yCount;
        for (let i = 0; i <= yCount; i++) {
            const y = margin.top + i * yStep;
            ctx.beginPath();
            ctx.moveTo(margin.left, y);
            ctx.lineTo(margin.left + chartWidth, y);
            ctx.stroke();
        }
    },

    // 绘制折线和数据点
    drawLineAndPoints(ctx, margin, chartWidth, chartHeight, priceTrend, minPrice, maxPrice) {
        const xStep = chartWidth / (priceTrend.length - 1);

        // 绘制折线
        ctx.beginPath();
        ctx.setStrokeStyle('#1890ff');
        ctx.setLineWidth(2);

        priceTrend.forEach((item, index) => {
            const x = margin.left + index * xStep;
            const yPercent = (item.avgPrice - minPrice) / (maxPrice - minPrice);
            const y = margin.top + chartHeight - yPercent * chartHeight;

            if (index === 0) {
                ctx.moveTo(x, y);
            } else {
                ctx.lineTo(x, y);
            }
        });

        ctx.stroke();

        // 绘制数据点
        priceTrend.forEach((item, index) => {
            const x = margin.left + index * xStep;
            const yPercent = (item.avgPrice - minPrice) / (maxPrice - minPrice);
            const y = margin.top + chartHeight - yPercent * chartHeight;

            ctx.beginPath();
            ctx.setFillStyle('#fff');
            ctx.setStrokeStyle('#1890ff');
            ctx.setLineWidth(2);
            ctx.arc(x, y, 4, 0, 2 * Math.PI);
            ctx.fill();
            ctx.stroke();
        });
    },

    // 绘制图例
    drawLegend(ctx, width, height) {
        ctx.setFontSize(12);
        ctx.setTextAlign('right');
        ctx.setTextBaseline('bottom');
        ctx.setFillStyle('#333');
        ctx.fillText('平均价格 (元)', width - 10, 20);
    },

    // 图表触摸事件处理
    onChartTouchStart(e) {
        this.handleChartTouch(e.touches[0]);
    },

    onChartTouchMove(e) {
        this.handleChartTouch(e.touches[0]);
    },

    onChartTouchEnd() {
        this.setData({
            showTooltip: false
        });
    },

    // 处理图表触摸逻辑
    handleChartTouch(touch) {
        const {
            chartInfo
        } = this.data;
        if (!chartInfo) return;

        const {
            margin,
            chartWidth,
            priceTrend,
            minPrice,
            maxPrice
        } = chartInfo;
        const {
            clientX,
            clientY
        } = touch;

        // 计算触摸点对应的日期和价格
        const xStep = chartWidth / (priceTrend.length - 1);
        const index = Math.round((clientX - margin.left) / xStep);

        if (index >= 0 && index < priceTrend.length) {
            const item = priceTrend[index];
            const date = new Date(item.date);
            const formattedDate = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;

            // 计算Y轴位置
            const yPercent = (item.avgPrice - minPrice) / (maxPrice - minPrice);
            const y = margin.top + chartWidth - yPercent * chartWidth;

            // 显示提示信息
            this.setData({
                showTooltip: true,
                tooltipDate: formattedDate,
                tooltipPrice: item.avgPrice,
                tooltipLeft: margin.left + index * xStep - 30,
                tooltipTop: y - 50
            });
        }
    },
    // 跳转到帖子详情
    goToPostDetail(e) {
        console.log(e);
        const postId = e.currentTarget.dataset.postid;
        wx.navigateTo({
            url: `/pages/postDetails/index?postId=${postId}`
        });
    },
    // 前往发帖页
    goToPublishPost() {
        if (!this.data.userInfo) {
            wx.showModal({
                title: '提示',
                content: '请先登录才能发帖',
                success: (res) => {
                    if (res.confirm) {
                        wx.navigateTo({
                            url: '/pages/login/login'
                        });
                    }
                }
            });
            return;
        }

        wx.navigateTo({
            url: '/pages/postAdd/index'
        });
    },
    // 跳转到商品详情
    goToGoodsDetail(e) {
        console.log(e);
        const goodsId = e.currentTarget.dataset.goodsid;
        wx.navigateTo({
            url: `/pages/goods/index?goodsId=${goodsId}`
        });
    }
});